<?php

namespace Database\Seeders;

use App\Models\Post;
use App\Models\User;
use App\Models\Category;
use App\Models\Tag;
use App\Models\Series;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 获取第一个用户作为所有文章的作者
        $author = User::first();
        if (!$author) {
            $this->command->error('没有找到用户，请先运行 UserSeeder');
            return;
        }
        $categories = Category::all();
        $tags = Tag::all();
        
        // 创建或获取"Laravel博客系统开发教学"系列
        $this->command->info('创建/获取系列...');
        $series = Series::firstOrCreate(
            ['slug' => 'laravel-blog-system-development-tutorial'],
            [
                'name' => 'Laravel博客系统开发教学',
                'description' => '本系列将详细介绍如何使用 Laravel 和 Vue.js 构建一个完整的博客系统，涵盖用户认证、内容管理、系列管理、评论交互、前端架构、服务层设计、API 数据交互、性能优化和搜索功能等核心模块。',
                'author_id' => $author->id,
                'post_count' => 0,
                'is_visible' => true,
                'meta_title' => 'Laravel博客系统开发教学',
                'meta_description' => '完整的 Laravel 博客系统开发教程，从零开始构建一个功能完善的博客平台。',
            ]
        );
        $this->command->line("  - 系列「{$series->name}」已准备就绪 (ID: {$series->id})");
        
        // 从 tutorials 目录读取文件并创建文章
        $this->command->info('从 tutorials 目录创建文章...');
        $tutorialsPath = base_path('docs/tutorials');
        
        if (!File::exists($tutorialsPath)) {
            $this->command->error("Tutorials 目录不存在: {$tutorialsPath}");
            return;
        }
        
        $tutorialFiles = File::files($tutorialsPath);
        $tutorialFiles = collect($tutorialFiles)
            ->filter(fn($file) => $file->getExtension() === 'md')
            ->sortBy(fn($file) => $file->getFilename())
            ->values();
        
        if ($tutorialFiles->isEmpty()) {
            $this->command->warn('没有找到 markdown 文件');
            return;
        }
        
        $createdPosts = collect();
        $order = 1;
        
        foreach ($tutorialFiles as $file) {
            $content = File::get($file->getPathname());
            
            // 从文件内容提取标题（第一个 # 标题）
            $title = $this->extractTitle($content, $file->getFilename());
            
            // 生成 slug
            $slug = Str::slug($title);
            
            // 检查是否已存在相同 slug 的文章
            $existingPost = Post::where('slug', $slug)->first();
            if ($existingPost) {
                $this->command->line("  - 文章「{$title}」已存在，跳过");
                continue;
            }
            
            // 提取摘要（前 200 个字符，去除 markdown 格式）
            $excerpt = $this->extractExcerpt($content);
            
            // 创建文章
            $publishedAt = now()->subDays($tutorialFiles->count() - $order);
            $post = Post::create([
                'title' => $title,
                'slug' => $slug,
                'content' => $content,
                'excerpt' => $excerpt,
                'author_id' => $author->id,
                'category_id' => $categories->isNotEmpty() ? $categories->random()->id : null,
                'series_id' => $series->id,
                'series_order' => $order,
                'sort_mode' => 'manual',
                'published_at' => $publishedAt,
                'views' => rand(50, 500),
                'allow_comments' => true,
                'featured' => $order <= 3, // 前3篇设为精选
            ]);
            
            // 关联标签
            if ($tags->isNotEmpty()) {
                $post->tags()->attach($tags->random(rand(2, 4)));
            }
            
            $createdPosts->push($post);
            $this->command->line("  - 创建文章「{$title}」（顺序：{$order}）");
            $order++;
        }
        
        // 更新系列的文章数量
        $series->update([
            'post_count' => Post::where('series_id', $series->id)
                ->published()
                ->count()
        ]);
        $this->command->line("  - 系列「{$series->name}」共有 {$series->post_count} 篇文章");

        // 批量更新分类统计
        $this->command->info('更新分类统计...');
        $categoryCounts = Post::whereNotNull('category_id')
            ->select('category_id', DB::raw('count(*) as count'))
            ->groupBy('category_id')
            ->pluck('count', 'category_id');

        foreach ($categoryCounts as $categoryId => $count) {
            DB::table('categories')
                ->where('id', $categoryId)
                ->update(['post_count' => $count]);
        }
        
        $this->command->info("成功创建 {$createdPosts->count()} 篇文章！");
    }

    /**
     * 从 markdown 内容中提取标题
     * 
     * @param string $content Markdown 内容
     * @param string $filename 文件名（作为后备）
     * @return string
     */
    private function extractTitle(string $content, string $filename): string
    {
        // 尝试提取第一个 # 标题
        if (preg_match('/^#\s+(.+)$/m', $content, $matches)) {
            $title = trim($matches[1]);
            // 如果标题是"Laravel博客系统开发教学"，尝试提取第二个标题
            if ($title === 'Laravel博客系统开发教学' && preg_match('/^##\s+(.+)$/m', $content, $matches)) {
                return trim($matches[1]);
            }
            return $title;
        }
        
        // 如果没有找到标题，使用文件名（去除扩展名和数字前缀）
        $name = pathinfo($filename, PATHINFO_FILENAME);
        $name = preg_replace('/^\d+[._-]/', '', $name); // 移除开头的数字和分隔符
        $name = str_replace(['_', '-'], ' ', $name);
        return ucwords($name);
    }

    /**
     * 从 markdown 内容中提取摘要
     * 
     * @param string $content Markdown 内容
     * @return string
     */
    private function extractExcerpt(string $content): string
    {
        // 移除第一个标题行
        $content = preg_replace('/^#+\s+.+$/m', '', $content, 1);
        
        // 移除代码块
        $content = preg_replace('/```[\s\S]*?```/', '', $content);
        
        // 移除行内代码
        $content = preg_replace('/`[^`]+`/', '', $content);
        
        // 移除链接和图片
        $content = preg_replace('/\[([^\]]+)\]\([^\)]+\)/', '$1', $content);
        $content = preg_replace('/!\[([^\]]*)\]\([^\)]+\)/', '', $content);
        
        // 移除 markdown 格式符号
        $content = preg_replace('/\*\*([^*]+)\*\*/', '$1', $content);
        $content = preg_replace('/\*([^*]+)\*/', '$1', $content);
        $content = preg_replace('/^[-*+]\s+/m', '', $content);
        $content = preg_replace('/^#+\s+/m', '', $content);
        
        // 移除多余空白
        $content = preg_replace('/\s+/', ' ', $content);
        $content = trim($content);
        
        // 提取前 200 个字符
        return Str::limit($content, 200);
    }
} 